/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/15 22:50
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

(function () {
    "use strict";

    var api = {
        "addCat": '/goods/category/addCat',
        "getCategoryUrl": '/goods/category/getLists',
        "setCatsUrl": '/goods/category/resetCats',
        "removeUrl": '/goods/category/remove',
        "getUnitsUrl": '/goods/unit/getLists',
        "addUnitUrl": '/goods/unit/addUnit',
        "removeUnitUrl": '/goods/unit/removeUnit'
    };

    sm.controller('admin-goods-category-controller', ['$scope', '$http', 'Modal', function ($scope, $http, Modal){

        $scope.categories = [];
        $scope.units = [];
        $scope.addParentCatName = '';
        $scope.addUnitName = '';

        var copyCats = [];

        // 获取总分类
        (function () {
            // 获取分类
            $http.get(api.getCategoryUrl).success(function (res) {
                if (res.state) {
                    $scope.categories = res.data;
                    copyCats = angular.copy(res.data);
                }
            });

            // 获取单位列表
            $http.get(api.getUnitsUrl).success(function (res) {
                if (res.state) {
                    $scope.units = res.data;
                }
            });
        })();

        $scope.addUnit = function () {
            if (!$scope.addUnitName) {
                return false;
            }
            // check repeat
            var repeat = false;
            angular.forEach($scope.units, function (val) {
                if (val['name'] == $scope.addUnitName) {
                    repeat = true;
                }
            });

            if (repeat) {
                Modal.alert('有相同计量单位存在');
                return false;
            }

            $http.post(api.addUnitUrl, {
                name: $scope.addUnitName
            }).success(function (res) {
                if (res.state) {
                    $scope.units.unshift(res.data);
                } else {
                    var err = res.error ? res.error : '添加失败';
                    Modal.error(err);
                }
            });
        };

        /**
         * 删除
         * @param key
         * @param id
         * @returns {boolean}
         */
        $scope.removeUnit = function (key, id) {
            if (!id) {
                return false;
            }

            Modal.alert({
                'title': '您确定删除此计量单位吗?',
                'content': '删除后不可恢复, 请谨慎操作!',
                'buttons': [{
                    'name': '取消',
                    'type': 'cancel'
                }, {
                    'name': '确认删除',
                    'event': function () {
                        doRemoveUnit(key, id);
                    }
                }]
            });

        };

        function doRemoveUnit(key, id) {
            $http.get(api.removeUnitUrl, {
                params: {
                    unitId: id
                }
            }).success(function (res) {
                if (res.state) {
                    $scope.units.splice(key, 1);
                } else {
                    var err = res.error ? res.error : '删除失败';
                    Modal.error(err);
                }
            });
        }

        /**
         * 添加父分类
         * @returns {boolean}
         */
        $scope.addPCat = function () {
            if (!$scope.addParentCatName) {
                return false;
            }

            if (checkIfRepeat($scope.addParentCatName)) {
                Modal.alert('分类名称 "'+$scope.addParentCatName+'" 已存在');
                $scope.addParentCatName = '';
                return false;
            }


            $http.post(api.addCat, {
                'name': $scope.addParentCatName
            }).success(function (res) {
                if (res.state) {
                    doAfterAdd(res.data);
                } else {
                    var err = res.error ? res.error : '分类添加失败';
                    Modal.error(err);
                }
            });
        };

        function doAfterAdd(data) {
            $scope.addParentCatName = '';
            $scope.categories.unshift(data);
            copyCats = angular.copy($scope.categories);
        }

        /**
         * 是否重复
         * @returns {boolean}
         */
        function checkIfRepeat(nowName) {
            var repeat = false;
            angular.forEach(copyCats, function (val) {
                if (nowName == val['name']) {
                    repeat = true;
                }

                if (val.subCats.length > 0) {
                    angular.forEach(val.subCats, function (v) {
                        if (nowName == v['name']) {
                            repeat = true;
                        }
                    });
                }
            });

            return repeat;
        }

        /**
         * 修改名称
         * @param type
         * @param id
         * @param value
         * @param index
         * @param key
         * @returns {boolean}
         */
        $scope.resetCat = function (type, id, value, index, key) {
            if (!id || !value) {
                return false;
            }

            $http.post(api.setCatsUrl, {
                catId: id,
                name: value
            }).success(function (res) {
                if (!res.state) {
                    var err = res.error ? res.error : '修改失败';
                    Modal.error(err);
                } else {
                    if (type == 'p'){
                        $scope.categories[index]['name'] = name;
                        copyCats = angular.copy($scope.categories);
                    } else {
                        $scope.categories[index]['subCats'][key]['name'] = name;
                        copyCats = angular.copy($scope.categories);
                    }
                }
            });

        };

        /**
         * 设置父排序
         * @param index
         * @param id
         * @param sort
         * @returns {boolean}
         */
        $scope.resetPSort = function (index, id, sort) {

            if (!id) {
                return false;
            }

            if (sort == copyCats[index]['sort']) {
                return false;
            }

            $http.post(api.setCatsUrl, {
                'catId': id,
                'sort': sort
            }).success(function (res) {
                if (!res.state) {
                    var err = res.error ? res.error : '排序修改失败';
                    Modal.error(err);
                } else {
                    $scope.categories[index]['sort'] = parseInt(sort);
                    copyCats = angular.copy($scope.categories);
                }
            });

        };

        /**
         * 删除父分类
         * @param index
         * @param id
         */
        $scope.remove = function (type, index, id, key) {

            if (!id){
                return false;
            }

            Modal.alert({
                'title': '您确定删除此分类吗?',
                'content': '删除后将无法恢复, 请谨慎操作!',
                'buttons': [{
                    'name': '取消',
                    'type': 'cancel'
                }, {
                    'name': '确定删除',
                    'event': function () {
                        doRemove(type, index, id, key);
                    }
                }]
            });
        };

        $scope.setSubBtn = function (id) {
            $scope['addSub_' + id] = true;
        };

        $scope.cancelSubBtn = function (id) {
            $scope['addSub_' + id] = false;
        };

        $scope.addSubCat = function (id, value, index) {

            if (!id || !value) {
                return false;
            }

            if (checkIfRepeat(value)) {
                Modal.alert('分类名称 "'+value+'" 已存在');
                return false;
            }

            $http.post(api.addCat, {
                parentId: id,
                name: value
            }).success(function (res) {
                if (res.state) {
                    $scope.categories[index]['subCats'].unshift(res.data);
                    $scope.subNewName = '';
                    $scope['addSub_' + id] = false;
                    copyCats = angular.copy($scope.categories);
                } else {
                    var err = res.error ? res.error : '分类添加失败';
                    Modal.error(err);
                }
            });


        };

        /**
         * 删除
         * @param index
         * @param id
         */
        function doRemove(type, index, id, key) {
            $http.get(api.removeUrl, {
                params: {
                    id: id
                }
            }).success(function (res) {
                if (!res.state) {
                    var err = res.error ? res.error : '删除失败';
                    Modal.error(err);
                } else {
                    if (type == 'p'){
                        // 父分类
                        $scope.categories.splice(index, 1);
                    } else {
                        $scope.categories[index]['subCats'].splice(key, 1);
                    }
                    copyCats = angular.copy($scope.categories);
                }
            });
        }

        // 排序
        $scope.resetSonSort = function ($index, key, id, sort) {
            if (!id) {
                return false;
            }

            // 与原值对比
            if (sort == copyCats[$index]['subCats'][key]['sort']) {
                return false;
            }

            $http.post(api.setCatsUrl, {
                catId: id,
                sort: sort
            }).success(function (res) {
                if (!res.state) {
                    var err = res.error ? res.error : '修改失败';
                    Modal.error(err);
                } else {
                    afterSort($index, key, res.data);
                }
            });
        };

        function afterSort ($index, key, data) {
            $scope.categories[$index]['subCats'][key] = data;
            copyCats = angular.copy($scope.categories);
        }

    }]);

})();